Skip to main content

Set

A Set is an object available as a data structure.

  • It has similarities and differences to Map and Object.

    • Map resemble Set the most.

Set stores unique values - which can be virtually anything.

info

Compared to mathematical sets, a Set in Hedgehog Script must have unique values with no duplication.

Here is an example of using Set:

One can iterate through a Set in insertion order just like a Map.

The way to add new elements to a Set is using add().

Any implementation of a Set is required to have, on average, sub-linear access times.

info

Just like maps, internally they can be like a hash table with \(\Omega(1)\) lookup time.

Then a search at \(\Omega(\log(N))\) time, and anything else (as long as its better than) with less than \(\Omega(N)\) time.

Set Methods

Here are some vital methods within Set:

  • Set.has(value)checks if a value is in that Set object

  • One can create a Set using the constructor Set()

  • An example instance property is: Set.size - (returns number of elements in Set)

  • Set.add() - Inserts a new element with a specified value in to a Set object, if there isn't one with the same value already

  • Set.clear() - Remove all elements from the Set object

  • Set.values(), Set.keys() and Set.entries() - returns an iterator that contains: values, keys and entries, respectively

  • Set.forEach() - Iterates through the values. Similar to Array.forEach() or Map.forEach()

Some examples of using the Set object:

tip

That was a long example! One thing to note is the last function:

  • it uses the mentioned method Set.forEach(), JSON, conditional ternary operator ? and an arrow function!

If one is confused this is how it works:

  • In insertion order, set1 is iterated over and runs the function which takes in value as the argument

  • Then it checks if a is an object: if so, parse it. Otherwise, keep it the same.

  • Then print the value - stringified, so objects can be shown!

 

info

There are quite a lot of elementary functions one can write and use.

More information can be found here: Sets - MDN.

Lastly, a practical function of Set is to decompose String:

  • Note that entries are stored as [value, value]

 

tip

A really good use of Sets is their ability to remove duplicate elements in Arrays:

Just transform the Array to a Set and then the Set back into an Array.